var CANVAS_W = 800;
var CANVAS_H = 600;
var SETTING = {start:{x:400, y:580}, angle:90.0, length:200};
var DATA =  [[30, 0.7], [-30, 0.6]];
var MAX_LEVEL = 3;

function main() {
	var ctx = document.getElementById('canvas').getContext('2d');
	draw_background(ctx, '#99cc33');
	ctx.strokeStyle = "white";
	ctx.fillStyle = "white"; 
	draw_tree(ctx, SETTING, 1);
}

function point(x, y) {
	return {x:x, y:y}
}

function A2R(angle) {
	return angle * Math.PI / 180.0;
}

function draw_background(ctx, color) {
	ctx.fillStyle=color;
	ctx.fillRect(0, 0, CANVAS_W, CANVAS_H);
}

function draw_line(ctx, p1, p2) {
	ctx.moveTo(p1.x, p1.y);
	ctx.lineTo(p2.x, p2.y);
	ctx.stroke();
}

function line_end(p, l, angle) {
	var r = A2R(angle);
	return {x:p.x + l * Math.cos(r),
					y:p.y - l * Math.sin(r)}
}

function draw_leaf(ctx, p, l, angle) {
	var p1 = line_end(p, l, angle);
	var r = l/1.414;
	var p2 = line_end(p, r, angle + 45);
	var p3 = line_end(p, r, angle - 45);
	ctx.beginPath();
	ctx.moveTo(p.x, p.y);
	ctx.lineTo(p1.x, p1.y);
	ctx.stroke();
	ctx.beginPath();
	ctx.moveTo(p.x, p.y);
	ctx.arcTo(p2.x,p2.y, p1.x, p1.y, r);
	ctx.arcTo(p3.x,p3.y, p.x, p.y, r);
	ctx.stroke();
}
 
function draw_tree(ctx, s, level) {
	var i;
	var a = s.angle;
	var l = s.length;
	var p = line_end(s.start, l, a);
	draw_trunk(ctx, s.start, l, a)
	if(level <= MAX_LEVEL) {	
		for(i = 0; i < DATA.length; ++i) {
			var b = DATA[i];
			var s2 = {start:p, angle:a + b[0], length:l * b[1]};
			draw_tree(ctx, s2, level + 1);
		}
	} else {
		var dl = l / 3;
		p = s.start;
		for(i = 0; i < 3; ++i) {
			p = line_end(p, dl, a);
			draw_leaf(ctx, p, dl, a + 30);
			draw_leaf(ctx, p, dl, a - 30);
		}
	}
}

function draw_polygon(ctx, points, fill) {  
    if(points.length > 2) {   
        var i;  
        var p = points[0];  
        ctx.beginPath();  
        ctx.moveTo(p.x, p.y);  
        for(i = 1; i < points.length; ++i) {  
            p = points[i];  
            ctx.lineTo(p.x, p.y);  
        }  
        ctx.closePath();  
        if(fill) {  
            ctx.fill();  
        } else {  
            ctx.stroke();  
        }  
    }  
}  
  
function draw_trunk(ctx, p, l, a) {  
    var w1 = l / 25, w2 = l / 40;  
    var p1 = line_end(p, w1, a + 90);  
    var p2 = line_end(p, w1, a - 90);  
    var t = line_end(p, l, a);  
    var p3 = line_end(t, w2, a + 90);  
    var p4 = line_end(t, w2, a - 90);  
    draw_polygon(ctx, [p1,p2,p4,p3], true);  
}  
